package router

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"go-admin-server/app/api"
	"go-admin-server/common/middleware"
	"time"
)

func InitRouter(logger *logrus.Logger) *gin.Engine {
	engine := gin.Default()

	engine.Use(
		costTimeMiddleware(),
		middleware.CORSMiddleware(),
		middleware.LogMiddleware(logger, "/"),
	)

	/*r.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {
		return fmt.Sprintf("【ClientIP】:%s - [%s] \"%s %s %s %d %s \"%s\" %s\"\n",
			param.ClientIP,
			param.TimeStamp.Format(time.RFC1123),
			param.Method,
			param.Path,
			param.Request.Proto,
			param.StatusCode,
			param.Latency,
			param.Request.UserAgent(),
			param.ErrorMessage,
		)
	}))*/

	apiV1 := engine.Group("/v1/app")
	api.NewPublicHttp(apiV1)
	api.NewLoginHttp(apiV1)
	api.NewUploadHttp(apiV1)

	apiV1.Use(middleware.CheckJWTAuthMiddleware())
	api.NewRoleHttp(apiV1)

	apiV1.Use()
	return engine
}

func costTimeMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 请求前获取当前时间
		nowTime := time.Now()
		// 请求处理
		c.Next()
		// 请求处理完获取花费的时间
		costTime := time.Since(nowTime)
		requestURL := c.Request.URL.String()
		fmt.Printf("[the request URL] %s [cost] %v\n", requestURL, costTime)
	}
}
